/*
 * @Author: WangShuai 1830773767@qq.com
 * @Date: 2025-05-12 15:44:23
 * @LastEditors: WangShuai 1830773767@qq.com
 * @LastEditTime: 2025-05-14 15:23:08
 * @FilePath: \cesium_visualBasic\src\1.白膜加载.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import * as Cesium from 'cesium'
import * as dat from 'dat.gui'
import {
    update3dtilesMaxtrix
} from './utils';
import {
    TencentImageryProvider
} from './utils/mapPlugin'
Cesium.Ion.defaultAccessToken = window.config.token;
const gui = new dat.GUI();
const viewer = new Cesium.Viewer('cesiumContainer');
//添加地图
const tencentImageryProvider = new TencentImageryProvider({
    style: "4",
    crs: "WGS84"
})
viewer.imageryLayers.addImageryProvider(tencentImageryProvider)
//添加白膜
const tile = new Cesium.Cesium3DTileset({
    url: "http://localhost:8888/shanghai/tileset.json"
});

const tileset = viewer.scene.primitives.add(tile);

tileset.readyPromise.then(() => {
    //给模型着色.通过3DtilleStyle语法
    tileset.style = new Cesium.Cesium3DTileStyle({
        color: {
            conditions: [
                ["Number(${Elevation})<20", "color('rgb(6, 202, 88)',1)"],
                ["Number(${Elevation})>20", "color('rgb(7, 169, 250)',1)"],
                ['true', 'color("blue")']
            ],
            show: false,
        },
    });

    //更新3Dtiles包围盒
    const boundingShpere = tileset.boundingSphere;
    viewer.camera.flyToBoundingSphere(boundingShpere);

    const offset = {
        tx: 0,
        ty: 0,
    }
    // 定义水域外观相关变量
    let waterAppearance = new Cesium.EllipsoidSurfaceAppearance({
        material: new Cesium.Material({
            fabric: {
                type: "Water",
                uniforms: {
                    baseWaterColor: new Cesium.Color(
                        64 / 255.0,
                        157 / 255.0,
                        253 / 255.0,
                        0.5
                    ),
                    normalMap: "/src/assets/waterNormals.jpg",
                    frequency: 1000.0, //频率
                    animationSpeed: 0.1,
                    amplitude: 10, //波浪大小
                    specularIntensity: 10, //反射强度
                }
            }
        })
    });
    //加载水域
    const loadRiver = async () => {
        let data = await Cesium.GeoJsonDataSource.load("/src/assets/shanghai_river.json")
        console.log("水域数据加载完成", data);

        let entitys = data.entities.values;

        // const appearance = new Cesium.EllipsoidSurfaceAppearance({
        //     material:new Cesium.Material({
        //         fabric:{
        //             type:"Water",
        //             uniforms:{
        //                 baseWaterColor:new Cesium.Color(
        //                         64 / 255.0,
        //                         157 / 255.0,
        //                         253 / 255.0,
        //                         0.5
        //                 ),
        //                 normalMap:"/src/assets/waterNormals.jpg",
        //                 frequency:1000.0,
        //                 animationSpeed:0.1,
        //                 specularIntensity:10,
        //             }
        //         }
        //     })
        // })

        const instance = [];
        entitys.forEach((e) => {
            let geometry = new Cesium.GeometryInstance({
                geometry: new Cesium.PolygonGeometry({
                    polygonHierarchy: new Cesium.PolygonHierarchy(
                        e.polygon.hierarchy.getValue().positions
                    ),
                    extrudedHeight: 0,
                    height: 0,
                    vertexFormat: Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT,
                })
            })
            instance.push(geometry)
        });

        const waterPrimitive = new Cesium.GroundPrimitive({
            geometryInstances: instance,
            appearance: waterAppearance,
            asynchronous: false,
        })

        viewer.scene.primitives.add(waterPrimitive)

        // 新增：计算水域边界并跳转到该区域
        // testCameraJump(); // 测试相机跳转
    }
    // 替换 calculateWaterExtentAndFly 函数为固定位置测试
    function testCameraJump() {
        // 使用一个已知的经纬度位置（这里使用武汉黄鹤楼作为示例）
        const position = Cesium.Cartesian3.fromDegrees(104.09360345849882, 30.626932186211427, 100);

        viewer.camera.flyTo({
            destination: position,
            orientation: {
                heading: Cesium.Math.toRadians(0.0),
                pitch: Cesium.Math.toRadians(-30.0),
                roll: 0.0
            },
            duration: 3.0
        });
    }

    loadRiver()

    gui.add(offset, 'tx', -1000, 1000, 1).onChange(
        () => {
            update3dtilesMaxtrix(offset.tx, offset.ty, tileset)
        }
    )
    gui.add(offset, 'ty', -1000, 1000, 1).onChange(() => {
        update3dtilesMaxtrix(offset.tx, offset.ty, tileset)
    })


    // 使用dat.gui调整水域流速和颜色
    const waterConfig = {
        speed: 0.1, // 初始流速
        red: 64 / 255.0,
        green: 157 / 255.0,
        blue: 253 / 255.0,
        alpha: 0.5,
        amplitude: 10,
    };

    gui.add(waterConfig, 'speed', 0, 1).name('水域流速').onChange((value) => {
        waterAppearance.material.uniforms.animationSpeed = value;
    });
    gui.add(waterConfig, 'amplitude', 0, 10, 1).name('波浪大小').onChange((value) => {
        waterAppearance.material.uniforms.amplitude = value;
    });

    gui.add(waterConfig, 'red', 0, 1).name('水域颜色 - 红').onChange((value) => {
        waterAppearance.material.uniforms.baseWaterColor = new Cesium.Color(
            value,
            waterConfig.green,
            waterConfig.blue,
            waterConfig.alpha
        );
    });

    gui.add(waterConfig, 'green', 0, 1).name('水域颜色 - 绿').onChange((value) => {
        waterAppearance.material.uniforms.baseWaterColor = new Cesium.Color(
            waterConfig.red,
            value,
            waterConfig.blue,
            waterConfig.alpha
        );
    });

    gui.add(waterConfig, 'blue', 0, 1).name('水域颜色 - 蓝').onChange((value) => {
        waterAppearance.material.uniforms.baseWaterColor = new Cesium.Color(
            waterConfig.red,
            waterConfig.green,
            value,
            waterConfig.alpha
        );
    });

    gui.add(waterConfig, 'alpha', 0, 1).name('水域颜色 - 透明度').onChange((value) => {
        waterAppearance.material.uniforms.baseWaterColor = new Cesium.Color(
            waterConfig.red,
            waterConfig.green,
            waterConfig.blue,
            value
        );
    });
});